{% extends 'layout.html' %}
{% load static %}

<!-- 前端代码 -->
{% block css %}
<style>
    .chart-row {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 20px;
        margin-bottom: 20px;
    }
    .chart-container {
        background: white;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
</style>
{% endblock %}

{% block content %}
<h1 style="text-align: center">热搜舆情深度分析</h1>
<div class="filter-bar">
    <select id="hotSelect" class="form-control" style="margin-bottom: 20px">
        <option value="">加载热榜...</option>
    </select>
</div>

<div class="chart-row">
    <div class="chart-container">
        <div id="timeChart" style="height:400px"></div>
    </div>
    <div class="chart-container">
        <div id="likeChart" style="height:400px"></div>
    </div>
</div>

<div class="chart-row">
    <div class="chart-container">
        <div id="wordChart" style="height:400px"></div>
    </div>
    <div class="chart-container">
        <div id="wordcloudChart" style="height:400px"></div>
    </div>
</div>
{% endblock %}

{% block js %}
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/echarts-wordcloud@2.0.0/dist/echarts-wordcloud.min.js"></script>
<script>
const COLORS = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE'];
let charts = {
    time: echarts.init(document.getElementById('timeChart')),
    like: echarts.init(document.getElementById('likeChart')),
    word: echarts.init(document.getElementById('wordChart')),
    wordcloud: echarts.init(document.getElementById('wordcloudChart'))
};

// 初始化热榜选择器
async function initHotSelect() {
    const res = await fetch('/api/hot_boards/');
    const hots = await res.json();
    const select = document.getElementById('hotSelect');

    select.innerHTML = hots.map(hot =>
        `<option value="${hot.id}">${hot.rank}. ${hot.keyword}</option>`
    ).join('');

    select.addEventListener('change', loadData);
    if (hots.length) select.value = hots[0].id;
}

// 加载数据
async function loadData() {
    const hotId = document.getElementById('hotSelect').value;
    if (!hotId) return;

    try {
        // 显示加载状态
        Object.values(charts).forEach(chart => chart.showLoading());

        const res = await fetch(`/hot_data_analysis/?hot_board_id=${hotId}`);
        const data = await res.json();

        // 更新时间趋势图
        updateTimeChart(data.time);
        // 更新点赞分布
        updateLikeChart(data.likes);
        // 更新热词图表
        updateWordChart(data.words);
        // 更新词云
        updateWordcloud(data.words);
    } catch (error) {
        console.error('加载失败:', error);
    } finally {
        Object.values(charts).forEach(chart => chart.hideLoading());
    }
}

// 更新时间趋势图
function updateTimeChart(data) {
    const option = {
        title: { text: '时间分布趋势', left: 'center' },
        color: [COLORS[0]],
        xAxis: {
            type: 'category',
            data: data.xAxis,
            name: '时间段'
        },
        yAxis: { type: 'value', name: '评论数' },
        tooltip: { trigger: 'axis' },
        series: [{
            data: data.data,
            type: 'bar',
            barWidth: '70%',
            itemStyle: {
                borderRadius: [5, 5, 0, 0]
            }
        }]
    };
    charts.time.setOption(option);
}

// 更新点赞分布
function updateLikeChart(data) {
    const option = {
        title: { text: '点赞区间分布', left: 'center' },
        color: COLORS,
        tooltip: { trigger: 'item' },
        series: [{
            type: 'pie',
            radius: '60%',
            data: data.categories.map((name, i) => ({
                name,
                value: data.data[i],
                itemStyle: { color: COLORS[i % 5] }
            })),
            label: {
                formatter: '{b}: {d}%'
            }
        }]
    };
    charts.like.setOption(option);
}

// 更新热词图表
function updateWordChart(data) {
    const option = {
        title: { text: '热词 Top10', left: 'center' },
        color: [COLORS[1]],
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'value' },
        yAxis: {
            type: 'category',
            data: data.top_words,
            axisLabel: { interval: 0 }
        },
        series: [{
            data: data.word_counts,
            type: 'bar',
            itemStyle: {
                borderRadius: [0, 5, 5, 0],
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                    { offset: 0, color: COLORS[1] },
                    { offset: 1, color: COLORS[3] }
                ])
            }
        }]
    };
    charts.word.setOption(option);
}

// 更新词云
function updateWordcloud(data) {
    const option = {
        title: { text: '舆情词云', left: 'center' },
        tooltip: { show: true },
        series: [{
            type: 'wordCloud',
            shape: 'circle',
            sizeRange: [20, 80],
            rotationRange: [0, 0],
            gridSize: 10,
            drawOutOfBound: false,
            textStyle: {
                color: () => COLORS[Math.floor(Math.random() * 5)]
            },
            data: data.wordcloud
        }]
    };
    charts.wordcloud.setOption(option);
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    // 初始化热榜选择器后自动加载数据
    initHotSelect().then(() => {
        // 添加1秒延迟确保DOM更新完成
        setTimeout(() => {
            if (document.getElementById('hotSelect').value) {
                loadData();
            }
        }, 1000);
    });

    window.addEventListener('resize', () => {
        Object.values(charts).forEach(chart => chart.resize());
    });
});

// 修改初始化函数为异步
async function initHotSelect() {
    try {
        const res = await fetch('/api/hot_boards/');
        const hots = await res.json();
        const select = document.getElementById('hotSelect');

        select.innerHTML = hots.map(hot =>
            `<option value="${hot.id}">${hot.rank}. ${hot.keyword}</option>`
        ).join('');

        select.addEventListener('change', loadData);

        // 设置默认值后直接触发加载
        if (hots.length) {
            select.value = hots[0].id;
            // 立即触发数据加载
            setTimeout(() => loadData(), 300);
        }
    } catch (error) {
        console.error('加载热榜失败:', error);
        select.innerHTML = '<option value="">数据加载失败</option>';
    }
}
</script>
{% endblock %}